<script setup lang="tsx">
import { message } from "@/utils/message";
import { useUserStoreHook } from "@/store/modules/user";
import type { FormInstance, FormRules } from "element-plus";
import ReCropperPreview from "@/components/ReCropperPreview";
import {
  createFormData,
  deviceDetection,
  isEmail,
  isPhone
} from "@pureadmin/utils";
import uploadLine from "@iconify-icons/ri/upload-line";
import { userInfoType, FileType } from "@/store/types";
import { upload } from "@/api/upload";
import { addDialog } from "@/components/ReDialog";
import dialogFrom from "./form.vue";
import { $t, transformI18n } from "@/plugins/i18n";
import { updatePhoneOrEmail } from "@/api/user";
defineOptions({
  name: "Profile"
});

const imgSrc = ref("");
const cropperBlob = ref();
const cropRef = ref();
const uploadRef = ref();
const isShow = ref(false);
const userInfoFormRef = ref<FormInstance>();
const userStore = useUserStoreHook();
const userInfos = reactive({
  sex: 0,
  avatar: "",
  nickName: "",
  email: "",
  phone: "",
  description: ""
});

const rules = reactive<FormRules<userInfoType>>({
  nickName: [{ required: true, message: "昵称必填", trigger: "blur" }],
  email: [{ validator: checkEmail, trigger: "blur" }],
  phone: [{ validator: checkPhone, trigger: "blur" }]
});
function checkEmail(rule: any, value: any, callback: any) {
  if (value && !isEmail(value)) {
    return callback(new Error("请输入正确的邮箱"));
  }
  callback();
}
function checkPhone(rule: any, value: any, callback: any) {
  if (value && !isPhone(value)) {
    return callback(new Error("请输入正确的手机号"));
  }
  callback();
}

const onChange = uploadFile => {
  const reader = new FileReader();
  reader.onload = e => {
    imgSrc.value = e.target.result as string;
    isShow.value = true;
  };
  reader.readAsDataURL(uploadFile.raw);
  addDialog;
};

const handleClose = () => {
  cropRef.value.hidePopover();
  uploadRef.value.clearFiles();
  isShow.value = false;
};

const onCropper = ({ blob }) => {
  cropperBlob.value = blob;
};

const handleSubmitImage = () => {
  const formData = createFormData({
    file: [{ raw: cropperBlob.value }]
  });
  upload(formData).then(async (res: FileType) => {
    userStore.SET_AVATAR(res.url);
    Object.assign(userInfos, { avatar: res.url });
    handleClose();
  });
};

// 更新信息
const onSubmit = async (formEl: FormInstance) => {
  await formEl.validate(async valid => {
    if (!valid) return;
    await userStore.updateUserInfo(userInfos);
  });
};
function _addDialog(type: number) {
  addDialog({
    title: type == 1 ? "修改邮箱" : "修改手机号",
    center: true,
    width: "500px",
    closeOnClickModal: false,
    contentRenderer: () => h(dialogFrom),
    props: { formInline: { type } },
    beforeSure: async (done, { options }) => {
      const from = options.props.formInline;
      console.log("from=====", from);
      if (!from.value) {
        return type == 2
          ? message(transformI18n($t("login.purePhoneCorrectReg")), {
              type: "error"
            })
          : message(transformI18n($t("login.pureEmailCorrectReg")), {
              type: "error"
            });
      }
      if (!from.code)
        return message(transformI18n($t("login.pureVerifyCodeReg")), {
          type: "error"
        });
      await updatePhoneOrEmail(from);
      done();
    }
  });
}

useUserStoreHook()
  .getUserInfo()
  .then(res => {
    Object.assign(userInfos, res);
  });
</script>

<template>
  <div
    :class="[
      'min-w-[180px] m-auto',
      deviceDetection() ? 'max-w-[100%]' : 'max-w-[70%]'
    ]"
  >
    <h3 class="my-8">个人信息</h3>
    <el-form
      ref="userInfoFormRef"
      label-position="top"
      :rules="rules"
      :model="userInfos"
    >
      <el-form-item label="头像">
        <el-avatar :size="80" :src="userInfos.avatar" />
        <el-upload
          ref="uploadRef"
          accept="image/*"
          action="#"
          :limit="1"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="onChange"
        >
          <el-button plain class="ml-4">
            <IconifyIconOffline :icon="uploadLine" />
            <span class="ml-2">更新头像</span>
          </el-button>
        </el-upload>
      </el-form-item>
      <el-form-item label="昵称" prop="nickName">
        <el-input
          v-model="userInfos.nickName"
          placeholder="请输入昵称"
          clearable
        />
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-radio-group v-model="userInfos.sex">
          <el-radio :value="1">男</el-radio>
          <el-radio :value="0">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <div class="mr-10 bg-gray-200 px-2 w-[250px] color">
          {{ userInfos.email }}
        </div>
        <el-button type="info" @click="_addDialog(1)">修改邮箱</el-button>
      </el-form-item>
      <el-form-item label="联系电话" prop="email">
        <div class="mr-10 bg-gray-200 px-2 w-[250px] color">
          {{ userInfos.phone }}
        </div>
        <el-button type="info" @click="_addDialog(2)">联系电话</el-button>
      </el-form-item>
      <el-form-item label="简介">
        <el-input
          v-model="userInfos.description"
          placeholder="请输入简介"
          type="textarea"
          :autosize="{ minRows: 6, maxRows: 8 }"
          maxlength="56"
          show-word-limit
        />
      </el-form-item>
      <el-button type="primary" @click="onSubmit(userInfoFormRef)">
        更新信息
      </el-button>
    </el-form>
    <el-dialog
      v-model="isShow"
      width="40%"
      title="编辑头像"
      destroy-on-close
      :closeOnClickModal="false"
      :before-close="handleClose"
      :fullscreen="deviceDetection()"
    >
      <ReCropperPreview ref="cropRef" :imgSrc="imgSrc" @cropper="onCropper" />
      <template #footer>
        <div class="dialog-footer">
          <el-button bg text @click="handleClose">取消</el-button>
          <el-button bg text type="primary" @click="handleSubmitImage">
            {{ $t("login.pureDefinite") }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
